package com.monkeyk.sos.web.controller.unity;

import com.leimingtech.core.common.IdGen;
import com.monkeyk.sos.domain.dto.UserJsonDto;
import com.monkeyk.sos.service.OauthRetrofitService;
import com.monkeyk.sos.service.OauthToken;
import com.monkeyk.sos.service.UserService;
import com.monkeyk.sos.utils.RetrofitUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

import static com.monkeyk.sos.utils.RetrofitUtils.CLIENT_ID_UNITY;
import static com.monkeyk.sos.utils.RetrofitUtils.CLIENT_SECURITY_UNITY;

/**
 * @author Shengzhao Li
 */
@Controller
@RequestMapping("/unitytoken/")
@Slf4j
public class UnityTokenController {

    @Autowired
    private UserService userService;

    @RequestMapping("dashboard")
    public String dashboardCode(String code, String state, HttpServletRequest request) {
        if (StringUtils.isEmpty(code) || StringUtils.isBlank(state)) {
            return "error/error";
        }
        String sessState = (String) request.getSession().getAttribute("unityState");
        if (StringUtils.isBlank(sessState) || !sessState.equals(state)) {
            return "error/error";
        }

        OauthRetrofitService oauthRetrofitService = RetrofitUtils.getOauthRetrofitService();
        OauthToken oauthToken = null;
        try {
            oauthToken = oauthRetrofitService.getAccessToken(CLIENT_ID_UNITY, CLIENT_SECURITY_UNITY, RetrofitUtils.GrantType.authorization_code.name(), code, RetrofitUtils.oauthServerHost + "unitytoken/dashboard").execute().body();

        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return "redirect:" + RetrofitUtils.oauthServerHost + "unity/dashboard?access_token=" + oauthToken.getAccess_token();
    }

    @RequestMapping("redirect")
    public String dashboardRedirect(HttpServletRequest request) {
        String state = IdGen.genSn(request);
        request.getSession().setAttribute("unityState", state);
        return "redirect:" + RetrofitUtils.oauthServerHost + "oauth/authorize?client_id=" + CLIENT_ID_UNITY + "&redirect_uri=" + RetrofitUtils.oauthServerHost + "unitytoken/dashboard&response_type=code&scope=read&state=" + state;
    }

    @RequestMapping("user_info")
    @ResponseBody
    public UserJsonDto userInfo() {
        return userService.loadCurrentUserJsonDto();
    }

}